<?php

namespace Admin\Controller;

use Common\Controller\AdminbaseController;
use Common\Model\LiveWemeModel;
use Common\Model\LiveFriendCircleModel;
use Common\Model\LiveWemeNicknameModel;

/**
 * Description of WemeextController
 *
 * @author
 */
class WemeextController extends AdminbaseController {

    function _initialize() {

        parent::_initialize();
        $this->_mod = D('LiveWeme');
        $this->assign('is_forward', [100 => '未转发', 1 => '已转发']);
        $this->assign('device', [1 => '行车记录仪', 2 => '采集端']);

        $this->user_admin_model = D("Common/AdminUser");
        $admin_id = $_SESSION["ADMIN_ID"];
        $this->company_id = $this->user_admin_model->where(array('admin_id' => $admin_id))->getField('company_id');
        $this->list_live_id = D('Common/Live')->where(array('company_id' => $this->company_id, "category" => 7))->select();
    }

    function index() {
        $map = $this->_search();
        $mod = $this->_mod;
        if (!empty($mod)) {
            $result = $this->_list($mod, $map);
            $this->assign('page', $result['page']);
            $list = $result['list'];
            foreach ($list as $key => $val) {
                $list[$key]['nickname'] = D('LiveWemeNickname')->where(array('mirrtalkID' => $val['mirrtalkid']))->getField('nickname');
            }
            $area_list = D('Company')->select();
            foreach ($area_list as $key => $value) {
                $area_list[$key]['area_id'] = D('Area')->where(array('name' => $value['city']))->getField('area_id');
                $area_list[$key]['character'] =$this->_getFirstCharter($value['city']);
            }
            $area_list = $this->_sysSortArray($area_list, "character");
            $this->assign('area_list', $area_list);
            $this->assign('list', $list);
            $this->display();
        }
    }

    public function send_weme() {
        if ($this->_request('action')) {
            if ($this->_request('type') == 7) {
                $id = $this->_request('id');
                $area = $this->_request('area');
                $area = explode(",", $area);
                $res = $this->_mod->where(array('id' => $id))->save(array('company_id' => $area[0], 'is_forward' => 1, 'area_id' => $area[1]));
                $res ? $this->ajaxReturn(array("status" => 1, "info" => "发布成功")) : $this->ajaxReturn(array("status" => 0, "info" => "发布失败！"));
            }

            if ($this->_request('type') == 1) {
                $id = $this->_request('id');
                !$this->_request('cover') && $this->ajaxReturn(array("status" => 0, "info" => "未上传图片！"));
                $weme = $this->_mod->where(array('id' => $id))->find();
                $weme_nickname = D('LiveWemeNickname')->where(array('mirrtalkID' => $weme['mirrtalkid']))->find();
                !$weme_nickname['nickname'] && $this->ajaxReturn(array("status" => 0, "info" => "昵称不能为空"));
                $data['author'] = $weme_nickname['nickname'];
                $data['avatar'] = $weme_nickname['url'];
                $data['authorid'] = $weme_nickname['id'];
                $data['subject'] = $this->_request('content');
                $data['dateline'] = time();
                $data['status'] = 32;
                $data['url'] = $weme['url'];
                $data['icon'] = $this->_request('cover');
                $_friend_circle_id = array();
                foreach ($this->list_live_id as $key => $value) {
                    $data['live_id'] = $value['live_id'];
                    $res = D('LiveFriendCircle')->add($data);
                    $_friend_circle_id[] = $res;
                }
                
                $data_friend_circle_id=implode(',',$_friend_circle_id);

                if ($weme['status'] == 0) {
                    $this->_mod->where(array('id' => $id))->save(array('status' => 2));
                }
                if ($weme['status'] == 1) {
                    $this->_mod->where(array('id' => $id))->save(array('status' => 3));
                }
                
                $cms_backend_api =M("vrlive.live_setting",null)->where(array('name' =>'cms_backend_api'))->getField('data');

                $fp = fsockopen("ssl://".$cms_backend_api, 443, $errno, $errstr); 
                if (!$fp) {
                    echo "$errstr ($errno)<br />\n";
                } else {
                    $out = "GET /upload-video/index?timestamp=123456789&app_key=helloword&unique=xinhuiwen%2Cfighting!&sign=4873c8c194f6b57327c53b06f1c4ec5e&url=".$weme['url']."&weme_id=".$id ."&friend_circle_id=".$data_friend_circle_id ." HTTPS/1.1\r\n";
                    $out .= "Host: fz3.cms.api.xinhuiwen.com\r\n";
                    $out .= "Connection: Close\r\n\r\n";
                    fwrite($fp, $out);
                    fclose($fp);
                    
                }                
                    $res ? $this->ajaxReturn(array("status" => 1, "info" => "发布成功", "data" => $data_friend_circle_id)) : $this->ajaxReturn(array("status" => 0, "info" => "发布失败！"));
              
            }

            if ($this->_request('type') == 6) {
                $id = $this->_request('id');
                $gallery = D('LiveGallery')->where(array('id' => $id))->find();
                $weme_nickname = D('LiveWemeNickname')->where(array('id' => rand(2, 15)))->find();
                $data['author'] = $gallery['nickname'];
                $data['avatar'] = $weme_nickname['url'];
                $data['authorid'] = $weme_nickname['id'];
                $data['subject'] = $this->_request('content');
                $data['dateline'] = time();
                $data['status'] = 32;
                $data['url'] = $gallery['url'];
                $res = D('LiveFriendCircle')->add($data);
                if ($gallery['status'] == 0) {
                    D('LiveGallery')->where(array('id' => $id))->save(array('status' => 2));
                }
                if ($gallery['status'] == 1) {
                    D('LiveGallery')->where(array('id' => $id))->save(array('status' => 3));
                }
                $res ? $this->ajaxReturn(array("status" => 1, "info" => "发布成功")) : $this->ajaxReturn(array("status" => 0, "info" => "发布失败！"));
                return;
            }
            if ($this->_request('type') == 0) {
                $id = $this->_request('id');
                $weme = $this->_mod->where(array('id' => $id))->find();
                if ($weme['status'] == 0) {
                    $this->_mod->where(array('id' => $id))->save(array('status' => 1));
                }
                if ($weme['status'] == 2) {
                    $this->_mod->where(array('id' => $id))->save(array('status' => 3));
                }
                return;
            }
            if ($this->_request('type') == 3) {
                $id = $this->_request('id');
                $gallery = D('LiveGallery')->where(array('id' => $id))->find();
                if ($gallery['status'] == 0) {
                    D('LiveGallery')->where(array('id' => $id))->save(array('status' => 1));
                }
                if ($gallery['status'] == 2) {
                    D('LiveGallery')->where(array('id' => $id))->save(array('status' => 3));
                }
                return;
            }
        }
        if ($this->_request('type') == 0) {
            $id = $this->_request('id');
            $weme = $this->_mod->where(array('id' => $id))->find();
            $this->assign('videos', $weme['url']);
        }
        if ($this->_request('type') == 3) {
            $id = $this->_request('id');
            $gallery = D('LiveGallery')->where(array('id' => $id))->find();
            $this->assign('files', $gallery['url']);
        }
        $this->assign('id', $this->_request('id'));
        $this->assign('type', $this->_request('type'));
        $area_list = D('Company')->where(array('status' => 1))->select();
        foreach ($area_list as $key => $value) {
            $area_list[$key]['area_id'] = D('Area')->where(array('name' => $value['city']))->getField('area_id');
            $area_list[$key]['character'] =$this->_getFirstCharter($value['city']);
        }
        $area_list = $this->_sysSortArray($area_list, "character");
        $this->assign('area_list', $area_list);
        $this->display();
    }

    public function send_list() {
        $where['status'] = array('exp', ' IN (1,3) ');
        $where['category'] = array('exp', ' IN (3,4,5) ');
        $live_list = D('Live')->where($where)->select();
        echo json_encode($live_list);
    }

    public function area_list() {
        $area_list = D('Area')->select();
        echo json_encode($area_list);
    }

    public function delete() {
        $map['id'] = $this->_request('id');
        $res = $this->_mod->where($map)->delete();
        $res ? $this->ajaxReturn(array("status" => 1, "info" => "删除成功")) : $this->ajaxReturn(array("status" => 0, "info" => "删除失败！"));
    }

    protected function _list($model, $map = array(), $sort_by = '', $order_by = '', $field_list = '*', $pagesize = 20) {
        //排序
        $mod_pk = $model->getPk();
        if ($this->_request("sort", 'trim')) {
            $sort = $this->_request("sort", 'trim');
        } else if (!empty($sort_by)) {
            $sort = $sort_by;
        } else if ($this->sort) {
            $sort = $this->sort;
        } else {
            $sort = $mod_pk;
        }
        if ($this->_request("order", 'trim')) {
            $order = $this->_request("order", 'trim');
        } else if (!empty($order_by)) {
            $order = $order_by;
        } else if ($this->order) {
            $order = $this->order;
        } else {
            $order = 'DESC';
        }
        $result = array();
        //如果需要分页
        if ($pagesize) {
            $count = $model->where($map)->count($mod_pk);
            $pager = $this->page($count, $pagesize);
        }
        $select = $model->field($field_list)->where($map)->order($sort . ' ' . $order);
        $this->list_relation && $select->relation(true);
        if ($pagesize) {
            $select->limit($pager->firstRow . ',' . $pager->listRows);
            $page = $pager->show('Admin');
            $result['page'] = $page;
            $this->assign("page", $page);
        }
        $list = $select->select();
        $result['list'] = $list;
        $this->assign('list_table', true);
        return $result;
    }

    protected function _search() {
        $map = array();
        ($author = $this->_request('author', 'trim')) && $map['mirrtalkID'] = array('IN', $this->_get_uids($author, 'nickname'));
        ($company_id = $this->_request('company_id', 'trim')) && $map['company_id'] = $company_id;
        ($device = $this->_request('device', 'trim')) && $map['device'] = $device;
        ($area_name = $this->_request('area_name', 'trim')) && $map['area_name'] = $area_name;
        if ($this->_request('is_forward')) {
            $is_forward = ($this->_request('is_forward') != 100) ? $this->_request('is_forward') : 0;
            $map['is_forward'] = $is_forward;
        }
        ($time_start = $this->_request('stime', 'trim')) && $map['mtime'] = array(array('egt', strtotime($time_start)), array('lt', strtotime($this->_request('etime', 'trim'))));
        $this->assign('search', array(
            'author' => $this->_request('author'),
            'stime' => $this->_request('stime'),
            'etime' => $this->_request('etime'),
            'is_forward' => $this->_request('is_forward'),
            'company_id' => $this->_request('company_id'),
            'area_name' => $this->_request('area_name'),
            'device' => $this->_request('device'),
        ));
        return $map;
    }

    protected function _request($parama) {
        return I($parama);
    }

    protected function _get_uids($keyword, $field) {
        $where[$field] = array('like', '%' . $keyword . '%');
        $uidarr = D('LiveWemeNickname')->where($where)->field('mirrtalkid')->select();
        $_idarr = array();
        foreach ($uidarr as $v) {
            $_idarr[] = $v['mirrtalkid'];
        }
        return implode(',', $_idarr);
    }

    protected function _sysSortArray($ArrayData, $KeyName1, $SortOrder1 = "SORT_ASC", $SortType1 = "SORT_REGULAR") {
        if (!is_array($ArrayData)) {
            return $ArrayData;
        }
        $ArgCount = func_num_args();
        for ($I = 1; $I < $ArgCount; $I ++) {
            $Arg = func_get_arg($I);
            if (!eregi("SORT", $Arg)) {
                $KeyNameList[] = $Arg;
                $SortRule[] = '$' . $Arg;
            } else {
                $SortRule[] = $Arg;
            }
        }
        foreach ($ArrayData AS $Key => $Info) {
            foreach ($KeyNameList AS $KeyName) {
                ${$KeyName}[$Key] = $Info[$KeyName];
            }
        }
        $EvalString = 'array_multisort(' . join(",", $SortRule) . ',$ArrayData);';
        eval($EvalString);
        return $ArrayData;
    }

    protected function _getFirstCharter($str) {
        if (empty($str)) {
            return '';
        }
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z'))
            return strtoupper($str{0});
        $s1 = iconv('UTF-8', 'gb2312', $str);
        $s2 = iconv('gb2312', 'UTF-8', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284)
            return 'A';
        if ($asc >= -20283 && $asc <= -19776)
            return 'B';
        if ($asc >= -19775 && $asc <= -19219)
            return 'C';
        if ($asc >= -19218 && $asc <= -18711)
            return 'D';
        if ($asc >= -18710 && $asc <= -18527)
            return 'E';
        if ($asc >= -18526 && $asc <= -18240)
            return 'F';
        if ($asc >= -18239 && $asc <= -17923)
            return 'G';
        if ($asc >= -17922 && $asc <= -17418)
            return 'H';
        if ($asc >= -17417 && $asc <= -16475)
            return 'J';
        if ($asc >= -16474 && $asc <= -16213)
            return 'K';
        if ($asc >= -16212 && $asc <= -15641)
            return 'L';
        if ($asc >= -15640 && $asc <= -15166)
            return 'M';
        if ($asc >= -15165 && $asc <= -14923)
            return 'N';
        if ($asc >= -14922 && $asc <= -14915)
            return 'O';
        if ($asc >= -14914 && $asc <= -14631)
            return 'P';
        if ($asc >= -14630 && $asc <= -14150)
            return 'Q';
        if ($asc >= -14149 && $asc <= -14091)
            return 'R';
        if ($asc >= -14090 && $asc <= -13319)
            return 'S';
        if ($asc >= -13318 && $asc <= -12839)
            return 'T';
        if ($asc >= -12838 && $asc <= -12557)
            return 'W';
        if ($asc >= -12556 && $asc <= -11848)
            return 'X';
        if ($asc >= -11847 && $asc <= -11056)
            return 'Y';
        if ($asc >= -11055 && $asc <= -10247)
            return 'Z';
        return null;
    }

}
